package com.biscuit.page.basicservice.interceptor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.biscuit.page.basicservice.bean.RedisCache;
import com.biscuit.page.basicservice.conf.handler.UserContextHandler;
import com.biscuit.page.basicservice.model.constant.redis.RedisAuthorizationConstant;
import com.biscuit.page.basicservice.model.entities.mysql.SysUser;
import com.biscuit.page.basicservice.model.entities.mysql.SysUserDetail;
import com.biscuit.page.basicservice.service.AuthorizationService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 用户信息存储拦截器
 *
 * @author mazihao
 * @createTime 2024/4/15 16:29
 */
@Slf4j
@Component
public class UserInfoInterceptor implements HandlerInterceptor {

    @Resource
    private RedisCache redisCache;

    @Resource
    private AuthorizationService authorizationService;

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {

        // 从请求头中获取用户认证 Token
        String authorization = request.getHeader("Authorization");

        // 判断 token 是否为空，不为空则进行解析校验
        if (StringUtils.isNotBlank(authorization)) {
            try {
                // 根据 token 获取用户信息
                SysUser sysUser = this.authorizationService.getUserInfoByTokenNoError(authorization);

                // 判断是否成功获取到用户信息
                if (Objects.nonNull(sysUser)) {
                    // 根据 userId 获取缓存中的用户详情信息
                    SysUserDetail sysUserDetail =
                            this.redisCache.get2Json(
                                    RedisAuthorizationConstant.AUTHORIZATION_USER_DETAIL_PREFIX + sysUser.getId(),
                                    SysUserDetail.class
                            );

                    // 设置用户信息到请求线程变量中
                    UserContextHandler.setContext(sysUser);
                    UserContextHandler.setContext(sysUserDetail);
                    UserContextHandler.setAuthorization(authorization);
                }
            } catch (Exception e) {
                log.warn("UserInfoInterceptor warn，message -> {}", JSON.toJSONString(e));
            }
        }

        return true;
    }

    @Override
    public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception {
        UserContextHandler.clear();
    }

}
